package main

import (
	"fmt"
	"text/template"
	"unsafe"
)

type Student struct {
	name string
}

func main() {
	declarePoint()
	accessPrivateField()
	convert()
	//值交换
	testSwap()
	testNewAssign()
	testSquare()
}

func declarePoint() {
	var a int
	var ptr *int
	var pptr **int
	ptr = &a
	pptr = &ptr
	a = 245
	fmt.Println("a:", a)
	fmt.Println("ptr", *ptr)
	fmt.Println("pptr", **pptr)
	//修改值 **pptr= 232 *ptr = 232 a =232
	**pptr = 212
	fmt.Println("a:", a)
	fmt.Println("ptr", *ptr)
	fmt.Println("pptr", **pptr)
	//
	var b int
	b = 45
	scope(&b)
	fmt.Println("通过指针可以修改：", b)
}

/**访问结构体的私成员*/
func accessPrivateField() {
	t := template.New("tangkaijun")
	student := (*Student)(unsafe.Pointer(t))
	student.name = "唐开军" //访问私有成员变量
	fmt.Println(student, t)
}

func convert() {
	u := uint32(32)
	i := int32(1)
	fmt.Println(&u, &i)
	p := &i
	p = (*int32)(unsafe.Pointer(&u))
	fmt.Println(*p)
}

func scope(p *int) {
	*p = 23
}

//实用指针交换
func swapRef(a, b *int) {
	c := *a
	*a = *b
	*b = c
}

func swapV(a, b int) {
	c := a
	a = b
	b = c
}

func testSwap() {
	var (
		a int
		b int
	)
	a = 4
	b = 5
	fmt.Println("V交换前:", "a=", a, "b=", b)
	swapV(a, b)
	fmt.Println("V交换后:", "a=", a, "b=", b)

	swapRef(&a, &b)
	fmt.Println("Ref交换后:", "a=", a, "b=", b)

}

func assign(a, b *int) {
	*a = 23
	*b = 43
}

func testNewAssign() {
	//实用new创建变量
	aa := new(int) //实用new关键字创建的变量返回的是地址
	bb := new(int)
	assign(aa, bb)
	fmt.Println("aa=", *aa, "bb=", *bb)
}

func square(x *float64) {
	*x = *x * *x
}

func testSquare() {
	a := 1.5
	square(&a)
	fmt.Println("平方后是:", a)
}
